using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace RSInterpretator
{
    public class TokenCollection : List<Token>
    {
        public TokenCollection()
        {

        }

        public void Split(string pattern)
        {
            int i = 0;
            while(i < this.Count)
            {
                Token token = this[i];
                if (token.IsMultiply)
                {
                    Match m = Regex.Match(token.Text, pattern);
                    if(m.Success)
                    {
                        string leftText = token.Text.Substring(0, m.Index).Trim();
                        string middleText = m.Value.Trim();
                        string rightText = token.Text.Substring(m.Index + m.Value.Length).Trim();
                        
                        this.Remove(token);

                        if(leftText.Length > 0)
                            this.Insert(i++, new Token(leftText, true));

                        if(middleText.Length > 0)
                            this.Insert(i++, new Token(middleText, false));

                        if(rightText.Length > 0)
                            this.Insert(i++, new Token(rightText, true));

                        i = 0;
                        continue;
                    }
                }

                i += 1;
            }
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            foreach (Token token in this)
                sb.Append(sb.ToString());

            return sb.ToString();
        }
    }

    public class Token
    {
        public Token(string text, bool isMultiply)
        {
            m_text = text;
            m_isMultiply = isMultiply;
        }

        private string m_text;
        private bool m_isMultiply;

        public bool IsMultiply
        {
            get { return m_isMultiply; }
            set { m_isMultiply = value; }
        }

        public string Text
        {
            get { return m_text; }
            set { m_text = value; }
        }

        public override string ToString()
        {
            return m_text;
        }
    }
}
